package io.jft.doll.room.repository

import com.g.base.extend.runDataBaseTransition
import com.g.base.room.repository.BaseRepository
import com.g.base.room.repository.NetworkBoundResult
import com.google.gson.JsonObject
import io.jft.doll.api.RoomApi
import io.jft.doll.api.apiProvider
import io.jft.doll.api.apiProviderMock
import io.jft.doll.room.database.AppDatabase
import io.jft.doll.room.entity.common.RoomCEntity
import kotlin.concurrent.thread

/**
 * Created by G on 2017/11/29 0029.
 */
class RoomRepository : BaseRepository() {
    companion object {
        //改变房间状态
        fun changeRoomStats(id: String, status: Int) {
            thread {
                val roomDao = AppDatabase.instant.getRoomDao()
                val roomSync = roomDao.getRoomSync(id) ?: return@thread
                AppDatabase.instant.runDataBaseTransition {
                    roomSync.status = status
                    roomDao.updateRoom(roomSync)
                }
            }
        }

        //预约房间
        fun appointmentRoom(id: String) {
            thread {
                val roomDao = AppDatabase.instant.getRoomDao()
                val wantAppointmentRoom = roomDao.getRoomSync(id) ?: return@thread
                val appointmentRoom = roomDao.getAppointmentRoom()
                AppDatabase.instant.runDataBaseTransition {
                    if (appointmentRoom != null) {
                        appointmentRoom.isAppointment = false
                        appointmentRoom.queued = appointmentRoom.normalQueued
                    }
                    wantAppointmentRoom.isAppointment = true
                    wantAppointmentRoom.normalQueued = wantAppointmentRoom.queued

                    if (appointmentRoom != null)
                        roomDao.updateRoom(appointmentRoom, wantAppointmentRoom)
                    else
                        roomDao.updateRoom(wantAppointmentRoom)
                }
            }
        }

        //取消预约房间
        fun abortAppointmentRoom(id: String) {
            thread {
                val roomDao = AppDatabase.instant.getRoomDao()
                val appointmentRoom = roomDao.getRoomSync(id) ?: return@thread
                if (appointmentRoom.isAppointment)
                    AppDatabase.instant.runDataBaseTransition {
                        appointmentRoom.isAppointment = false
                        appointmentRoom.queued = appointmentRoom.normalQueued
                        roomDao.updateRoom(appointmentRoom)
                    }
            }
        }

        //改变我的排队状态
        fun changeQueue(id: String, queue: Int, isAppointment: Boolean) {
            thread {
                val roomSync = AppDatabase.instant.getRoomDao().getRoomSync(id) ?: return@thread
                AppDatabase.instant.runDataBaseTransition {
                    val roomDao = getRoomDao()
                    if (isAppointment) {
                        roomSync.queued = queue
                    } else {
                        roomSync.normalQueued = queue
                        roomSync.queued = queue
                    }
                    roomDao.updateRoom(roomSync)
                }
            }
        }

        //清除本地房间缓存
        fun nukeRoomTable() {
            thread {
                AppDatabase.instant.runDataBaseTransition {
                    getRoomDao().nukeTable()
                }
            }
        }
    }

    //获取频道列表
    fun getChannelList(jsonObject: JsonObject) = NetworkBoundResult(
            {
                apiProviderMock.create(RoomApi::class.java).getChannelList(jsonObject)
            }
    )

    /**
     * 获取房间列表
     * */
    fun getRoomList(jsonObject: JsonObject): NetworkBoundResult<List<RoomCEntity>?> {
        val groupId = jsonObject.get("groupId")?.asString ?: "-1"
        val limit = jsonObject.get("offset").asInt + jsonObject.get("limit").asInt

        return NetworkBoundResult(
                {
                    apiProvider.create(RoomApi::class.java).getRoomList(jsonObject)
                },
                loadFormDb = {
                    AppDatabase.instant.getRoomDao().getGroupRoomList(groupId, limit)
                },
                shouldRemote = {
                    it == null || it.size < limit
                },
                saveRemoteResult = {
                    AppDatabase.instant.runDataBaseTransition {
                        it!!
                        for (item in it)
                            item.groupId = groupId
                        getRoomDao().insertRoom(*it.toTypedArray())
                    }
                }
        )
    }

    //获取房间详情
    fun getRoomDetail(id: String): NetworkBoundResult<RoomCEntity?> {
        return NetworkBoundResult(
                {
                    apiProvider.create(RoomApi::class.java)
                            .getRoomDetail(JsonObject().apply { addProperty("id", id) })
                },
                shouldRemote = { true },
                loadFormDb = { AppDatabase.instant.getRoomDao().getRoom(id) },
                saveRemoteResult = {
                    it!!
                    it.id = id
                    val roomSync = AppDatabase.instant.getRoomDao().getRoomSync(id)
                    if (roomSync != null) {
                        if (roomSync.isAppointment)
                            it.queued = roomSync.queued
                        it.normalQueued = it.queued
                        it.isAppointment = roomSync.isAppointment
                        it.groupId = roomSync.groupId
                        it.img = roomSync.img
                        it.thumbnail = roomSync.thumbnail
                        it.title = roomSync.title
                        it.status = roomSync.status
                    }
                    AppDatabase.instant.runDataBaseTransition {
                        getRoomDao().updateRoom(it)
                    }
                })
    }

    //获取娃娃详情
    fun getWawaDetail(id: String) = NetworkBoundResult({
        apiProviderMock.create(RoomApi::class.java).getDollDetail(
                JsonObject().apply {
                    addProperty("id", id)
                }
        )
    })

    //获取房间最近游戏记录
    fun getRoomGameHistory(id: String) = NetworkBoundResult({
        apiProviderMock.create(RoomApi::class.java).getRoomGameHistory(
                JsonObject().apply {
                    addProperty("id", id)
                }
        )
    })

    //获取房间最近抓娃娃达人
    fun getRoomWawaMaster(id: String) = NetworkBoundResult({
        apiProviderMock.create(RoomApi::class.java).getRoomDollMaster(
                JsonObject().apply {
                    addProperty("id", id)
                }
        )
    })

}